package com.lanou.zakerproject.subscribe;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lanou.zakerproject.R;
import com.lanou.zakerproject.base.VolleySingleton;
import com.lanou.zakerproject.tool.GsonRequest;
import com.lanou3g.greendaodemo.entity.greendao.DaoSingleton;
import com.lanou3g.greendaodemo.entity.greendao.GridViewEntity;
import com.lanou3g.greendaodemo.entity.greendao.GridViewEntityDao;
import com.lanou3g.greendaodemo.entity.greendao.NewsScrollEntity;
import com.lanou3g.greendaodemo.entity.greendao.NewsScrollEntityDao;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.widget.Toast;


/**
 * Created by dllo on 16/1/8.
 */
public class SubscribeFragment extends Fragment {

    private ViewPager mViewPager;//定义一个可以左右滑动的viewpager组件
    private String[] titles; //图片标题
    private List<View> dots; // 图片标题正文的那些点
    private TextView title;
    private int oldPosition = 0;//记录上一次点的位置
    private int currentItem; //当前页面-索引号
    private SubscribeScrollAdapter subscribeScrollAdapter;
    private ScheduledExecutorService scheduledExecutorService;//定时周期执行指定任务
    DisplayImageOptions options;//拉取网络数据
    List<String> res;
    private NewsScroll newsScroll;

    private static final int ARGS_WHAT = 0x1101;
    private static final int DELAY_TIME = 3000;
    private HandlerThread handlerThread;
    private Handler mHandler;
    private Handler handlers = new Handler();
    private boolean controlThread = false;

    private HeaderGridView gridView;
    private GridViewAdapter gridViewAdapter;
    private LinearLayout subLinearlayout;
    private View dotView;
    private ChannelSearch channelSearch;
    final NewsScrollEntityDao newsScrollEntityDao = DaoSingleton.getInstance().getRecommendDao();
    GridViewEntityDao gridViewEntityDao = DaoSingleton.getInstance().getGridViewEntityRecommendDao();
    List<NewsScrollEntity> newsScrollEntitylist;
    List<GridViewEntity> gridViewEntityList;
    GestureDetector mGestureDetector;
    private Context context;
    private String url = "http://iphone.myzaker.com/zaker/follow_promote.php?_appid=AndroidPhone&_bsize=1080_1920&_dev=97&_lat=4.9E-324&_lng=4.9E-324&_mac=08%3A00%3A27%3A3f%3A7a%3A" +
            "01&_mcode=B51557E3&_net=wifi&_nudid=7891a15eb7d34771&_os=5.1_GoogleNexus5-5.1.0-API22-1080x1920&_os_name=GoogleNexus5-5.1.0-API22-1080x1920&_udid=5.1_GoogleNexus5-5.1.0-API22-1080x1920.08%3A00%3A27%3A3f%3A7a%3A01&_v=6.4.5&_version=6.44&m=1452044270";
    private String url_channel = "http://iphone.myzaker.com/zaker/block_topic.php?_appid=AndroidPhone&_bsize=1080_1920&_dev=97&_lat=4.9E-324&_lng=4.9E-324&_mac=08%3A00%3A27%3A3f%3A7a%3A01&_mcode=B51557E3&_net=wifi&_nudid=7891a15eb7d34771&_os=5.1_GoogleNexus5-5.1.0-API22-1080x1920&_os_name=GoogleNexus5-5.1.0-API22-1080x1920&_udid=5.1_GoogleNexus5-5.1.0-API22-1080x1920.08%3A00%3A27%3A3f%3A7a%3A01&_v=6.4.5&_version=6.44&id=54dee8fa9490cbde430000ba";


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_subscribe, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        gridView = (HeaderGridView) view.findViewById(R.id.gridView_subscribe);
        View headView = LayoutInflater.from(context).inflate(R.layout.scroll_header, null);
        title = (TextView) headView.findViewById(R.id.scroll_title);
        dotView = headView.findViewById(R.id.dot_0);
        subLinearlayout = (LinearLayout) headView.findViewById(R.id.sub_lin);
        mViewPager = (ViewPager) headView.findViewById(R.id.viewPager_main_scroll);
        gridView.addHeaderView(headView);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        getRequsetData(url);//请求网络
        getRequsetChannelData(url_channel);

        // 设置一个监听器，当ViewPager中的页面改变时调用
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // TODO Auto-generated method stub
                title.setText(titles[position]);
                setChangeDots(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
            }
        });
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), NewsActivity.class);
                String pk = channelSearch.getData().getList().get(position - 3).getPk();
                intent.putExtra("channel_news_pk", pk);
                getActivity().startActivity(intent);
            }
        });
    }

    /**
     * e1  .手势起点的移动事件
     * e2  .当前手势点的移动事件
     * velocityX   .每秒x轴方向移动的像素
     * velocityY   .每秒y轴方向移动的像素
     */
//    class FragmentListener extends GestureDetector.SimpleOnGestureListener {
//        private int verticalMinDistance = 20;
//        private int minVelocity = 0;
//
//        @Override
//        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//            if (e1.getY() - e2.getY() < Math.abs(velocityX)) {
//                Toast.makeText(context, "从上向下滑", Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(context, CoverActivity.class);
//                startActivity(intent);
//                getActivity().overridePendingTransition(R.anim.slide_up_in, R.anim.slide_up_out);
//            } else if (e1.getY() - e2.getY() > Math.abs(velocityX)) {
//                Toast.makeText(context, "从下向上滑", Toast.LENGTH_SHORT).show();
//            } else if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {
//                Toast.makeText(context, "从左向右滑", Toast.LENGTH_SHORT).show();
//            } else if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {
//                Toast.makeText(context, "从右向左滑", Toast.LENGTH_SHORT).show();
//            }
//            return super.onFling(e1, e2, velocityX, velocityY);
//        }
//    }
    @Override
    public void onStart() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 当Activity显示出来后，每五秒钟切换一次图片显示
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 1, 5, TimeUnit.SECONDS);
        super.onStart();
    }

    private void initThread() {
        handlerThread = new HandlerThread("viewPager");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                runChangerPager();
                if (controlThread) {
                    mHandler.sendEmptyMessageDelayed(ARGS_WHAT, DELAY_TIME);
                }
            }
        };
    }

    private void runChangerPager() {
        handlers.post(new Runnable() {
            @Override
            public void run() {
                int index = mViewPager.getCurrentItem();
                mViewPager.setCurrentItem(index++);
            }
        });
    }

    //切换图片
    private class ViewPagerTask implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            currentItem = (currentItem + 1) % res.size();
            //更新界面
            handler.obtainMessage().sendToTarget();
        }
    }

    //     切换当前显示的图片
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //设置当前页面
            mViewPager.setCurrentItem(currentItem);// 切换当前显示的图片
        }
    };

    /**
     * 解析数据的方法
     *
     * @param urls 接口
     */
    private void getRequsetData(String urls) {
        GsonRequest<NewsScroll> gsonRequest = new GsonRequest<>(urls, NewsScroll.class, new Response.Listener<NewsScroll>() {
            @Override
            public void onResponse(NewsScroll response) {
                subscribeScrollAdapter = new SubscribeScrollAdapter(getActivity(), response.getData().getList(), 1);
                mViewPager.setAdapter(subscribeScrollAdapter);
                newsScroll = response;
                res = new ArrayList<String>();
                for (int i = 0; i < newsScroll.getData().getList().size(); i++) {
                    String url = newsScroll.getData().getList().get(i).getPromotion_img();
                    res.add(url);
                }
                //图片标题
                titles = new String[newsScroll.getData().getList().size()];
                for (int i = 0; i < newsScroll.getData().getList().size(); i++) {
                    titles[i] = newsScroll.getData().getList().get(i).getTitle();
                }
                subscribeScrollAdapter.notifyDataSetChanged();

                dots = new ArrayList<View>();
                setView(newsScroll.getData().getList().size());

                if (newsScrollEntityDao.queryBuilder().list() != null) {
                    newsScrollEntityDao.deleteAll();
                    addDB(response);
                } else {
                    addDB(response);
                }
                initThread();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 读数据库里数据
                newsScrollEntitylist = newsScrollEntityDao.queryBuilder().list();
                subscribeScrollAdapter = new SubscribeScrollAdapter(newsScrollEntitylist, getActivity(), 0);
                mViewPager.setAdapter(subscribeScrollAdapter);
                subscribeScrollAdapter.notifyDataSetChanged();
                //图片标题
                titles = new String[newsScrollEntitylist.size()];
                for (int i = 0; i < newsScrollEntitylist.size(); i++) {
                    titles[i] = newsScrollEntitylist.get(i).getTitle();
                }
            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void addDB(NewsScroll response) {
        newsScrollEntitylist = new ArrayList<>();
        for (int i = 0; i < response.getData().getList().size(); i++) {
            NewsScrollEntity newsScrollEntity = new NewsScrollEntity();
            newsScrollEntity.setPromotion_img(response.getData().getList().get(i).getPromotion_img());
            newsScrollEntity.setTitle(response.getData().getList().get(i).getTitle());
            newsScrollEntitylist.add(newsScrollEntity);
        }
        newsScrollEntityDao.insertInTx(newsScrollEntitylist);
    }

    /**
     * 解析数据的方法
     *
     * @param urls 接口
     */
    private void getRequsetChannelData(String urls) {
        GsonRequest<ChannelSearch> gsonRequest = new GsonRequest<>(urls, ChannelSearch.class, new Response.Listener<ChannelSearch>() {
            @Override
            public void onResponse(ChannelSearch response1) {
                gridViewAdapter = new GridViewAdapter(context, response1, 1);
                gridView.setAdapter(gridViewAdapter);
                channelSearch = response1;
                if (gridViewEntityDao.queryBuilder().list() != null) {
                    gridViewEntityDao.deleteAll();
                    addChannelDB(response1);
                } else {
                    addChannelDB(response1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 读数据库里数据
                gridViewEntityList = gridViewEntityDao.queryBuilder().list();
                gridViewAdapter = new GridViewAdapter(getActivity(), gridViewEntityList, 0);
                gridView.setAdapter(gridViewAdapter);
            }
        });
        VolleySingleton.getInstance()._addRequest(gsonRequest);
    }

    private void addChannelDB(ChannelSearch response1) {
        gridViewEntityList = new ArrayList<>();
        for (int i = 0; i < response1.getData().getList().size(); i++) {
            GridViewEntity gridViewEntity = new GridViewEntity();
            gridViewEntity.setTitle(response1.getData().getList().get(i).getTitle());
            gridViewEntity.setPic(response1.getData().getList().get(i).getPic());
            gridViewEntityList.add(gridViewEntity);
        }
        gridViewEntityDao.insertInTx(gridViewEntityList);
    }


    /**
     * 添加动态添加View
     * index 表示有几个点
     */
    private void setView(int num) {
        for (int i = 0; i < num; i++) {
            View view = new View(getActivity());
            view.setBackgroundResource(R.drawable.dot_focused);
            view.setLayoutParams(dotView.getLayoutParams());//设置控件的大小
            subLinearlayout.addView(view);
            dots.add(view);
        }
    }

    void setChangeDots(int index) {
        for (int i = 0; i < dots.size(); i++) {
            if (index == i) {
                dots.get(i).setBackgroundResource(R.drawable.dot_normal);
            } else {
                dots.get(i).setBackgroundResource(R.drawable.dot_focused);
            }
        }
    }

    /**
     * 删除点
     */
    private void removeView() {
        subLinearlayout.removeAllViews();
        dots.clear();
    }


//    @Override
//    public void onResume() {
//        super.onResume();
//        controlThread = true;
//        mHandler.sendEmptyMessage(ARGS_WHAT);
//    }

    @Override
    public void onStop() {
        // 当Activity不可见的时候停止切换
        scheduledExecutorService.shutdown();
        super.onStop();
    }
}
